From 68909b166e81d591d7923c549e344c568814ed2d Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Wed, 24 Jun 2020 21:40:30 -0500 Subject: [PATCH] Add instance_method_mock_fixture() for mocking instance methods --- src/pgwui_testing/testing.py | 18 ++++++++++++++++ tests/test_testing.py | 42 +++++++++++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/src/pgwui_testing/testing.py b/src/pgwui_testing/testing.py index a68f7a3..13010c7 100644 --- a/src/pgwui_testing/testing.py +++ b/src/pgwui_testing/testing.py @@ -73,3 +73,21 @@ def make_mock_fixture(module, method, autouse=False): monkeypatch.setattr(module, method, mocked) return mocked return fix + + +def instance_method_mock_fixture(method): + '''Returns a pytest fixture that mocks an instance method of a class. + "method" is a string. + + The fixture is called by the test function with the class instance + that's to be monkeypatched and the mock is returned for the + test function to configure/etc. + ''' + @fixture + def fix(monkeypatch): + def run(cls): + mocked = mock.Mock(spec=getattr(cls, method), name=method) + monkeypatch.setattr(cls, method, mocked) + return mocked + return run + return fix diff --git a/tests/test_testing.py b/tests/test_testing.py index 9266b0a..a27e397 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -110,6 +110,9 @@ def test_pgwui_component_entry_point(testdir): # Test functions +# +# make_mock_fixture() +# # Function to test mocking def func_to_mock(): @@ -120,7 +123,6 @@ mocked_func = testing.make_mock_fixture( sys.modules[__name__], 'func_to_mock') -# make_mock_fixture def test_make_mock_fixture_fixture(mocked_func): '''The mock of the function works ''' @@ -129,3 +131,41 @@ def test_make_mock_fixture_fixture(mocked_func): result = mocked_func() assert result == test_value + + +# +# instance_method_mock_fixture() +# + +normal_return_value = 'not mocked' + + +# Class for mock testing +class TestClass(): + + def method_to_mock(self): + return normal_return_value + + +mocked_method = testing.instance_method_mock_fixture('method_to_mock') + + +def test_instance_method_mock_fixture(mocked_method): + '''The mock of the instance method works + ''' + test_value = 'mocked value' + cls = TestClass() + mocked_method(cls).return_value = test_value + + result = cls.method_to_mock() + + assert result == test_value + + +def test_instance_method_mock_fixture_unmocked(): + '''The test class works after the mocking + ''' + cls = TestClass() + result = cls.method_to_mock() + + assert result == normal_return_value -- 2.34.1